#include <QtGui>
#include <QGLWidget>
#include <QtOpenGL>
#include <math.h>
#include "openGL_model.h"
#include "point3d.h"
#include "assert.h"
#include "planet_math.h"

#define MAX_GL_R 300

void drawSolidSphere(GLdouble radius, GLint slices, GLint stacks)
{
  glBegin(GL_LINE_LOOP);
    GLUquadricObj* quadric = gluNewQuadric();

    gluQuadricDrawStyle(quadric, GLU_FILL);
    gluSphere(quadric, radius, slices, stacks);

    gluDeleteQuadric(quadric);
  glEnd();
}

void GLScene::drawPoint(Point3D point)
{ 
  glBegin(GL_POINTS);
    qglColor(Qt::white);
    glVertex3d(point.x, point.y, point.z);
    qglColor(Qt::black);
  glEnd();
  glFlush();
}

void GLScene::drawTrajectory(QList<Point3D> point_list)
{
  assert(point_list.isEmpty() == false);
  for (QList<Point3D>::iterator it = point_list.begin(); it != point_list.end(); it++)
  {
    drawPoint(*it);
  }
}

double maxModelRadius(QList<PlanetMath> model)
{
  assert(model.isEmpty() == false);
  double maxR = 0.0;
  for (QList<PlanetMath>::iterator itPlanet = model.begin(); itPlanet != model.end(); itPlanet++)
  {
     for (QVector<Point3D>::iterator itPoint = (*itPlanet).path.begin(); itPoint != (*itPlanet).path.end(); itPoint++)
     {
       if ((*itPoint).AbsoluteValue() > maxR)
         maxR = (*itPoint).AbsoluteValue();
     }
  }
  return maxR;
}

void GLScene::drawModel(QList<PlanetMath> model)
{
  assert(model.isEmpty() == false);
  double max_model_radius = maxModelRadius(model);
  double max_GL_radius = MAX_GL_R;
  double eff_ratio = max_GL_radius/max_model_radius;

    for (QList<PlanetMath>::iterator itPlanet = model.begin(); itPlanet != model.end(); itPlanet++)
  {
     for (QVector<Point3D>::iterator itPoint = (*itPlanet).path.begin(); itPoint != (*itPlanet).path.end(); itPoint++)
     {
       drawPoint((*itPoint)*eff_ratio);
     }
  }
}